<template>

  <div class="app-container">
    <el-tabs v-model="activeName" class="demo-tabs" @tab-change="handleClick">
      <el-tab-pane label="活动汇总明细" name="活动汇总明细">
        <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
          <el-form-item label="活动名称" prop="activityName">
            <el-input v-model="queryParams.activityName" placeholder="请输入活动名称" clearable @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item label="活动部门" prop="activityDeptId" v-if="deptId==101">
            <el-tree-select style="width:100%" v-model="queryParams.activityDeptId" :data="deptOptions" @node-click="handleNodeClick($event,'queryParams')"
              :props="{ value: 'id', label: 'label', children: 'children' }" value-key="id" placeholder="请选择活动部门" check-strictly clearable />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>

        <el-table v-loading="loading" :data="activityList" @selection-change="handleSelectionChange" show-overflow-tooltip>

          <el-table-column label="序号" align="center" width="65" type="index" />
          <el-table-column label="活动名称" align="center" prop="activityName" width="100" />
          <el-table-column label="活动部门" align="center" prop="deptName" width="120" />
          <el-table-column label="活动时间" align="center" prop="activityTime" width="140">
            <template #default="scope">
              <span>{{ parseTime(scope.row.activityTime, '{y}-{m}-{d}') }}</span>
            </template>
          </el-table-column>
          <el-table-column label="活动类型" align="center" prop="activityType">
            <template #default="scope">
              <el-tag :type="getTagStyle(scope.row.activityType)">
                <dict-tag :options="activity_type" :value="scope.row.activityType" class="custom-dict-tag" />

              </el-tag>
            </template>
          </el-table-column>
       
          <el-table-column label="活动方案" align="center" prop="fileList" width="100">
            <template #default="scope">
              <el-button link type="primary" @click.stop="previewFun(scope.row.fileList[0]?.url)">{{scope.row.fileList[0]?.name}}</el-button>
            </template>
          </el-table-column>
          <el-table-column label="总结" align="center" prop="fileList" width="100">
            <template #default="scope">
              <el-button link type="primary" @click.stop="previewFun(scope.row.fileList[1]?.url)">{{scope.row.fileList[1]?.name}}</el-button>
            </template>
          </el-table-column>
          <el-table-column label="现场照片" align="center" prop="imgList" width="100">
            <template #default="scope">
              <image-preview :src="scope.row.imgList" :width="50" :height="50" />
            </template>
          </el-table-column>
          <el-table-column label="备注" align="center" prop="remark" />
          <el-table-column label="状态" align="center" prop="status" width="80">
            <template #default="scope">
              <span>{{scope.row.status==0?'未完成':'完成'}}</span>
            </template>
          </el-table-column>

          <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="100">
            <template #default="scope">
              <el-button link type="primary" icon="View" @click="showDetails(scope.row)" v-hasPermi="['charge:activity:edit']">查看详情</el-button>
            </template>
          </el-table-column>
        </el-table>

        <pagination v-show="total>0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />

        <!-- 添加或修改活动对话框 -->
        <el-dialog :title="title" v-model="open" width="1000px" append-to-body>
          <el-form ref="activityRef" :model="form" :rules="rules" label-width="80px">
            <el-row :gutter="15">
              <el-col :span="12">
                <el-form-item label="活动名称" prop="activityName">
                  <el-input v-model="form.activityName" placeholder="请输入活动名称" style="width:100%" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="活动部门" prop="activityDeptId">
                  <el-tree-select style="width:100%" v-model="form.activityDeptId" :data="deptOptions" @node-click="handleNodeClick($event,'form')"
                    :props="{ value: 'id', label: 'label', children: 'children' }" value-key="id" placeholder="请选择活动部门" check-strictly clearable />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="活动时间" prop="activityTime">
                  <el-date-picker style="width:100%" clearable v-model="form.activityTime" type="date" value-format="YYYY-MM-DD" placeholder="请选择活动时间">
                  </el-date-picker>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="活动类型" prop="activityType">
                  <el-select style="width:100%" v-model="form.activityType" placeholder="请选择活动类型">
                    <el-option v-for="dict in activity_type" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="活动方式" prop="activityMode">
                  <el-select style="width:100%" v-model="form.activityMode" placeholder="请选择活动方式">
                    <el-option v-for="dict in activity_mode" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
                  </el-select>
                </el-form-item>
              </el-col>

              <el-col :span="12">
                <el-form-item style="width:100%" label="活动人数" prop="activityPerson">
                  <el-input v-model="form.activityPerson" placeholder="请输入活动人数" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item style="width:100%" label="活动地点" prop="activityPlace">
                  <el-input v-model="form.activityPlace" placeholder="请输入活动地点" />
                </el-form-item>
              </el-col>
            </el-row>

            <el-form-item label="相关文件" prop="fileList">
              <!-- <div class="img-box">
                <CusUpload :modelValue="form.fileList1" @update:modelValue="updateValue($event,0)" :limit="1" :isShowTip="false" name="演练通知" />
                <div class="img-tips">演练通知</div>
              </div> -->
              <div class="img-box">
                <CusUpload :modelValue="form.fileList1" @update:modelValue="updateValue($event,0)" :isShowTip="false" name="活动方案" />
                <div class="img-tips">活动方案</div>
              </div>
              <!-- <div class="img-box">
                <CusUpload :modelValue="form.fileList2" @update:modelValue="updateValue($event,1)" :isShowTip="false" name="情况登记表" />
                <div class="img-tips">情况登记表</div>
              </div>
              <div class="img-box">
                <CusUpload :modelValue="form.fileList2" @update:modelValue="updateValue($event,1)" :isShowTip="false" name="效果评估表" />
                <div class="img-tips">效果评估表</div>
              </div> -->
              <div class="img-box">
                <CusUpload :modelValue="form.fileList2" @update:modelValue="updateValue($event,1)" :isShowTip="false" name="总结" />
                <div class="img-tips">总结</div>
              </div>
              <!-- <div class="img-box">
                <CusUpload :modelValue="form.fileList2" @update:modelValue="updateValue($event,1)" :isShowTip="false" name="签到表" />
                <div class="img-tips">签到表</div>
              </div> -->

            </el-form-item>
            <el-form-item label="现场照片" prop="imgList">
              <ImageUpload :modelValue="form.imgList" v-model="form.imgList" />
            </el-form-item>
            <el-form-item label="备注" prop="remark">
              <el-input style="width:100%" v-model="form.remark" type="textarea" placeholder="请输入内容" :rows="5" />
            </el-form-item>
          </el-form>
          <template #footer>
            <div class="dialog-footer">
              <el-button type="primary" @click="submitForm">确 定</el-button>
              <el-button @click="cancel">取 消</el-button>
            </div>
          </template>
        </el-dialog>
      </el-tab-pane>
      <el-tab-pane label="活动统计" name="活动统计">
        <el-form :model="querytSummaryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
          <el-form-item label="活动部门" prop="activityDeptId">
            <el-tree-select style="width:100%" v-model="querytSummaryParams.activityDeptId" :data="deptOptions"
              @node-click="handleNodeClick($event,'querytSummaryParams')" :props="{ value: 'id', label: 'label', children: 'children' }" value-key="id"
              placeholder="请选择活动部门" check-strictly clearable />
          </el-form-item>
          <el-form-item label="年度" prop="activityTime">
            <el-date-picker v-model="querytSummaryParams.activityTime" format="YYYY" value-format="YYYY" type="year" placeholder="请选择年份"
              @change="updateTimerValue" />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="Search" @click="handleSummaryQuery">搜索</el-button>
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>

        <el-table v-loading="loading" :data="summaryList" show-overflow-tooltip>
          <el-table-column label="序号" align="center" width="65" type="index" />
          <el-table-column label="活动部门" align="center" prop="deptName"  width="120"/>
          <el-table-column label="计划活动次数" align="center" prop="plan" width="120" />
          <el-table-column label="已完成活动次数" align="center" prop="finish" width="140" >
            <template #default="scope">
              <router-link to="/coordination/marketing/marketplan">{{scope.row.finish}}</router-link>
            </template>
          </el-table-column>
          <el-table-column label="已活动类型" align="center" prop="activityType" >
            <template #default="scope">
              <el-tag type="primary">
                <dict-tag :options="activity_type" :value="scope.row.activityType" /></el-tag>
            </template>
          </el-table-column>
          <el-table-column label="年度" align="center" prop="year" width="100" />

        </el-table>

        <pagination v-show="total>0" :total="summaryTotal" v-model:page="querytSummaryParams.pageNum" v-model:limit="querytSummaryParams.pageSize"
          @pagination="getSummaryList" />

      </el-tab-pane>
    </el-tabs>
    <Details :dialogVisible="isDetails" :rowDetails="rowDetails" @handleClose="handleClose" />
    <Viewer ref="fileViewerRef" :dialog-doc="dialogDoc" />
  </div>
</template>

<script setup name="Activity">
import { deptTreeSelect } from "@/api/system/user";
import { listActivity, getActivity, delActivity, addActivity, updateActivity, getStatistics } from "@/api/charge/activity";
import { getCKInfo } from '@/utils/auth'
import CusUpload from "@/components/Custom/CusUpload"
import Details from "./Details";
import Viewer from "@/components/Custom/viewer.vue";

const { proxy } = getCurrentInstance();
const { activity_type, activity_mode } = proxy.useDict('activity_type', 'activity_mode');
const baseUrl = import.meta.env.VITE_APP_BASE_API;

const activityList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const deptOptions = ref([])
const summaryList = ref([])
const summaryTotal = ref(0)
const activeName = ref('活动汇总明细')
const isDetails = ref(false)
const rowDetails = ref({})
const fileViewerRef = ref()
const dialogDoc = ref(false)
const deptId = ref(Number(getCKInfo('deptId')))


const data = reactive({
  form: {
    fileList: [],
    fileList1: [],
    fileList2: [],
    fileList3: [],
    fileList4: [],
    fileList5: [],
    fileList6: [],
  },
  querytSummaryParams: {
    pageNum: 1,
    pageSize: 10,
    activityTime: null,
    activityDeptId: null,

  },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    activityName: null,
    activityDeptId: null,
    status: null,
    status: 1
  },
  rules: {
  }
});

const { queryParams, form, rules, querytSummaryParams } = toRefs(data);
/** 查询部门下拉树结构 */
function getDeptTree() {
  deptTreeSelect().then(response => {
    deptOptions.value = response.data;
  });
};
/** 查询活动列表 */
function getList() {
  loading.value = true;
  listActivity(queryParams.value).then(response => {
    activityList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    activityName: null,
    activityDeptId: null,
    activityTime: null,
    activityType: null,
    activityMode: null,
    activityPlace: null,
    imgList: null,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null,
    remark: null,
    status: null,
    fileList: [],
    fileList1: [],
    fileList2: [],
    fileList3: [],
    fileList4: [],
    fileList5: [],
    fileList6: [],
  };
  proxy.resetForm("activityRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

function handleSummaryQuery() {
  querytSummaryParams.value.pageNum = 1;
  getSummaryList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加活动";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _id = row.id || ids.value
  getActivity(_id).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "修改活动";
  });
}
const showDetails = (row) => {
  const _id = row.id || ids.value;
  getActivity(_id).then(response => {
    rowDetails.value = response.data;
    isDetails.value = true;
  });
}
const handleClose = () => {
  isDetails.value = false;
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["activityRef"].validate(valid => {
    if (valid) {
      delete form.value.fileList1;
      delete form.value.fileList2;
      delete form.value.fileList3;
      delete form.value.fileList4;
      delete form.value.fileList5;
      delete form.value.fileList6;


      if (form.value.id != null) {
        updateActivity(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addActivity(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}
function handleNodeClick(data, name) {
  if (name == 'queryParams') {
    queryParams.value.activityDeptId = data.id;
  } else if (name == 'querytSummaryParams') {
    querytSummaryParams.value.activityDeptId = data.id;
  } else {
    form.value.activityDeptId = data.id;
  }


}
/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除活动编号为"' + _ids + '"的数据项？').then(function () {
    return delActivity(_ids);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => { });
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('charge/activity/export', {
    ...queryParams.value
  }, `活动汇总_${new Date().getTime()}.xlsx`)
}

const updateValue = (data, index) => {

  form.value.fileList[index] = data[0]
  form.value.fileList[index].activityId = data[0].uid
  form.value.fileList[index].id = data[0].uid
}

const handleClick = (val) => {
  if (val == '活动汇总明细') {
    getList()
  } else {
    getSummaryList()
  }

}
/** 查询活动列表 */
function getSummaryList() {
  loading.value = true;
  getStatistics(querytSummaryParams.value).then(response => {
    summaryList.value = response.rows;
    summaryTotal.value = response.total;
    loading.value = false;
  });
}

const getTagStyle = (status) => {
  const statusMap = {
    '4': 'danger',
    '3': 'warning',
    '2': 'info',
    '1': 'success',
    '0': 'primary'
  }
  return statusMap[status]
}


const updateTimerValue = (val) => {
  querytSummaryParams.value.activityTime = val;
}
// 预览
const previewFun = (file) => {
  dialogDoc.value = true;
  let data = {};
  // 上传过的文件组成完成的网络路径
  if (file&&file.indexOf(',')==-1) {
    data.src = `${baseUrl}${file}`;
  }else if(file&&file.indexOf(',')!=-1){
    let src=file.split(',');
    let srcArr=[]
    src.forEach(item=>{srcArr.push(`${baseUrl}${item}`)})
    data.src = srcArr.join(',');
    file=srcArr[0]
  }

  const arr = file.split(".");
  const suffix = arr[arr.length - 1];
  if (suffix == "docx" || suffix == "doc") {
    fileViewerRef.value?.viewDocx(data, '公文');
  } else if (suffix == "xlsx" || suffix == "xls") {
    fileViewerRef.value?.viewXlsx(data);
  } else if (suffix == "jpg" || suffix == "jpeg" || suffix == "png") {
    fileViewerRef.value?.viewImg(data);
  } else if (suffix == "pdf") {
    fileViewerRef.value?.viewPdf(data);
  }
};
getDeptTree()
getList();
</script>

<style scoped>
.img-box {
  margin-right: 15px;
}
.img-box .img-tips {
  font-size: 12px;
  line-height: 20px;
  text-align: center;
  margin-top: 10px;
}
.demo-tabs {
  margin-bottom: 20px;
}
.pagination-container {
  min-height: 80px;
}

.content-cus .el-descriptions__cell {
  border: none !important;
}
.border-top {
  border-top: 1px solid #ebeef5;
}
</style>
